package com.gdut.simple.data.local.db;

import android.content.Context;
import android.database.Cursor;

import com.gdut.simple.data.entity.History;

import java.util.List;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class DbManager {

    public static Observable<List<History>> queryHistory(Context context) {
        return DbModule.provideBriteDatabase(DbModule.provideSqlBrite(), DbModule.provideOpenHelper(context))
                .createQuery(History.Table.TABLE_NAME, "select * from " + History.Table.TABLE_NAME)
                .mapToList(History.Table.MAPPER)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public static Observable<History> queryHistory(Context context, String title, String url) {
        return DbModule.provideBriteDatabase(DbModule.provideSqlBrite(), DbModule.provideOpenHelper(context))
                .createQuery(History.Table.TABLE_NAME,
                        "select * from " + History.Table.TABLE_NAME + " where " + History.Table.COLUMN_TITLE + "=? and " + History.Table.COLUMN_URL + "=?",
                        title, url)
                .mapToOneOrDefault(History.Table.MAPPER, null)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public static long addHistory(Context context, History history) {
        return DbModule.provideBriteDatabase(DbModule.provideSqlBrite(), DbModule.provideOpenHelper(context))
                .insert(History.Table.TABLE_NAME, History.Table.INSERT(history));
    }

    public static int deleteHistory(Context context, int id) {
        return DbModule.provideBriteDatabase(DbModule.provideSqlBrite(), DbModule.provideOpenHelper(context))
                .delete(History.Table.TABLE_NAME, History.Table.ID + "=?", String.valueOf(id));
    }

    public static void clearHistory(Context context) {
        DbModule.provideBriteDatabase(DbModule.provideSqlBrite(), DbModule.provideOpenHelper(context))
                .execute("delete from " + History.Table.TABLE_NAME);
    }

}
